using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class GameJoystick : MonoBehaviour, IDragHandler, IPointerDownHandler, IPointerUpHandler, IEventSystemHandler
{
	public Image joyBackground;

	public Image joyButton;

	public float radius;

	public Vector2 RawValue
	{
		get
		{
			return joyButton.transform.localPosition;
		}
		set
		{
			if (value.magnitude > radius)
			{
				value = value.normalized * radius;
			}
			joyButton.transform.localPosition = value;
		}
	}

	public Vector2 Value
	{
		get
		{
			Vector2 result = joyButton.transform.localPosition;
			result.x *= 1f / radius;
			result.y *= 1f / radius;
			return result;
		}
	}

	private void Start()
	{
		joyButton.raycastTarget = false;
	}

	private void Update()
	{
	}

	private void OnEnable()
	{
		joyButton.transform.localPosition = Vector2.zero;
	}

	private void OnDisable()
	{
		joyButton.transform.localPosition = Vector2.zero;
	}

	public void OnDrag(PointerEventData eventData)
	{
		if (RectTransformUtility.ScreenPointToLocalPointInRectangle(joyBackground.rectTransform, eventData.position, eventData.pressEventCamera, out Vector2 localPoint))
		{
			if (localPoint.magnitude > radius)
			{
				localPoint = localPoint.normalized * radius;
			}
			joyButton.transform.localPosition = localPoint;
		}
	}

	public void OnPointerDown(PointerEventData eventData)
	{
		OnDrag(eventData);
	}

	public void OnPointerUp(PointerEventData eventData)
	{
		if (RectTransformUtility.ScreenPointToLocalPointInRectangle(joyBackground.rectTransform, eventData.position, eventData.pressEventCamera, out Vector2 _))
		{
			joyButton.transform.localPosition = Vector3.zero;
		}
	}
}
